package com.example.routelink.gateway.filter;

import cn.dev33.satoken.config.SaSignConfig;
import cn.dev33.satoken.sign.SaSignTemplate;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.example.routelink.gateway.entity.ResultData;
import com.example.routelink.gateway.entity.ResultEnum;
import com.example.routelink.gateway.utils.IpUtils;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class SensitiveFilterGatewayFilterFactory extends BaseFilter<SensitiveFilterGatewayFilterFactory.Config> implements Ordered {

    public SensitiveFilterGatewayFilterFactory() {
        super(SensitiveFilterGatewayFilterFactory.Config.class);
    }

    private final String filterName = "敏感词";

    private static List<String> sensitiveConfigWord;

    @Value("${sensitiveConfig}")
    private List<String> sensitiveConfig;

    @PostConstruct
    private void init() {
        sensitiveConfigWord = FileUtil.readUtf8Lines(System.getProperty("user.dir") + "\\config\\sensitiveConfigWord.txt");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            long startTime = System.currentTimeMillis();
            if (CollUtil.isEmpty(sensitiveConfig) || CollUtil.isEmpty(sensitiveConfigWord)) {
                writeLog(filterName, startTime, "校验失败 未配置敏感信息");
                return chain.filter(exchange);
            }
            String path = exchange.getRequest().getURI().getPath();
            Map<String, String> encryptionMap = exchange.getRequest().getQueryParams().toSingleValueMap();
            for (String sensitiveUrlGet : sensitiveConfig) {
                String configPath = sensitiveUrlGet.split("\\.")[0];
                if (!StrUtil.equals(path, configPath)) {
                    continue;
                }
                HttpMethod httpMethod = exchange.getRequest().getMethod();
                String contentType = exchange.getRequest().getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
                if (contentType != null && contentType.contains(MediaType.APPLICATION_JSON_VALUE) && httpMethod.equals(HttpMethod.POST)) {
                    Object cachedBody = exchange.getAttribute(ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR);
                    if (cachedBody != null) {
                        JSONObject json = JSON.parseObject(JSON.toJSONString(cachedBody));
                        for (String key : json.keySet()) {
                            encryptionMap.put(key, json.getString(key));
                        }
                    }
                }
                String configParameter = sensitiveUrlGet.split("\\.")[1];
                if (encryptionMap.containsKey(configParameter) && StrUtil.isNotEmpty(encryptionMap.get(configParameter))) {
                    String value = encryptionMap.get(configParameter);
                    for (String sensitiveWord : sensitiveConfigWord) {
                        if (value.contains(sensitiveWord)) {
                            writeLog(filterName, startTime, "校验失败 存在敏感词 {} url:{} 参数： {} 值： {}", sensitiveWord, configPath, configParameter, value);
                            return response(exchange, ResultEnum.ErrSensitive);
                        }
                    }
                }
            }
            writeLog(filterName, startTime, "校验通过");
            return chain.filter(exchange);
        };
    }

    @Data
    public static class Config {
        private String secretKey;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
